package com.cloudwise.gproject.controller;

import com.cloudwise.gproject.entity.Attendance;
import com.cloudwise.gproject.service.AttendanceService;
import com.cloudwise.gproject.util.Result;
import com.cloudwise.gproject.util.ReturnStatus;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (Attendance)表控制层
 *
 * @author makejava
 * @since 2021-03-25 10:25:49
 */
@Controller
@RequestMapping("attendance")
public class AttendanceController {
    /**
     * 服务对象
     */
    @Resource
    private AttendanceService attendanceService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ResponseBody
    @RequestMapping("selectOne")
    public Result selectOne(Integer id) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                this.attendanceService.queryById(id));
    }

    /**
     * 跳转部门分页列表页面
     *
     * @return
     */
    @RequestMapping("toPage")
    public String toPage() {
        return "back/attendance-page";
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @return 对象列表
     */
    @ResponseBody
    @RequestMapping("queryAll")
    public Result queryAll(Integer page, Integer limit, Attendance attendance) {
        ArrayList<Attendance> attendancesNew = findAttendancesNew(page, limit, attendance);
        System.out.println(attendancesNew);
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(),
                0, attendancesNew);
    }

    /**
     * 导入Excel
     *
     * @return 对象列表
     */
    @ResponseBody
    @RequestMapping("importAttendance")
    public Result importAttendance(@RequestParam MultipartFile file) {
        System.out.println("importVisit方法...");
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                attendanceService.importAttendance(file));
    }

    /**
     * 新增数据
     *
     * @param attendance 实例对象
     * @return 实例对象
     */
    @ResponseBody
    @RequestMapping("insert")
    public Result insert(Attendance attendance) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                this.attendanceService.insert(attendance));
    }

    /**
     * 修改数据
     *
     * @param attendance 实例对象
     * @return 实例对象
     */
    @ResponseBody
    @RequestMapping("update")
    public Result update(Attendance attendance) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                this.attendanceService.update(attendance));
    }

    /**
     * 通过主键删除数据
     *
     * @param attendanceId 主键
     * @return 是否成功
     */
    @ResponseBody
    @RequestMapping("deleteById")
    public Result deleteById(Integer attendanceId) {
        return new Result(ReturnStatus.SUCCESS.getCode(),
                ReturnStatus.SUCCESS.getMessage(), 0,
                this.attendanceService.deleteById(attendanceId));
    }

    /** 
     * @create by: 卫子健
     * @description: 图标显示 横坐标姓名 纵坐标早退次数 ，迟到次数 
     * @create time: 2021/3/26 13:54
     * @param startTime  endTime
     * @return com.cloudwise.gproject.util.Result 
     */
    @ResponseBody
    @RequestMapping("showAttendanceEchart")
    public Result showAttendanceEchart(String startTime,String endTime){
        /**
         * 方法；1.查出startTime-endTime时间段内所有有过签到记录的times(不重复的)
         *      2.遍历times，获取每一个time(每一天),每个人的签到，迟到状态(attendancesNew)
         *      3.定义两个map集合，迟到集合map1(name，inStatus),早退集合map2(name,outStatus)
         *      4.遍历attendancesNew，将迟到和早退的人名装进集合，key(inStatus或outStatus加一)
         *      5.获取出勤表中所有有过记录的人名(不重复的)names
         *      6.遍历names,将name与对应的inStatusCount和outStatusCount加进3个不同的数组中
         *      7.将三个数组加进mapNew集合中，返回mapNew
         */
        System.out.println(startTime+endTime);
        if (startTime == null || "".equals(startTime)) {
            startTime = "2000-01-01";
        }
        if (endTime == null || "".equals(endTime)) {
            endTime = "2100-01-01";
        }
        //查出startTime-endTime时间段内所有有过签到记录的times(不重复的)
        List<String> times = attendanceService.getTimes(startTime, endTime);
        //定义两个map集合，迟到集合map1(name，inStatus),早退集合map2(name,outStatus)
        HashMap<String, Integer> inStatusMap = new HashMap<>();
        HashMap<String, Integer> outStatusMap = new HashMap<>();
        //遍历times，获取每一个time(每一天),每个人的签到，迟到状态(attendancesNew)
        for (String time : times) {
            Attendance attendance = new Attendance();
            attendance.setAttendanceTime(time);
            ArrayList<Attendance> attendancesNew = findAttendancesNew(1, 100000, attendance);
            //遍历attendancesNew，将迟到和早退的人名装进集合，key(inStatus或outStatus加一)
            for (Attendance attendance1 : attendancesNew) {
                if (attendance1.getInStatus()==true){
                    Integer integer = inStatusMap.get(attendance1.getLoginName());
                    if (integer==null){
                        inStatusMap.put(attendance1.getLoginName(),1);
                    }else {
                        inStatusMap.put(attendance1.getLoginName(),integer+1);
                    }
                }
                if (attendance1.getOutStatus()==true){
                    Integer integer = outStatusMap.get(attendance1.getLoginName());
                    if (integer==null){
                        outStatusMap.put(attendance1.getLoginName(),1);
                    }else {
                        outStatusMap.put(attendance1.getLoginName(),integer+1);
                    }
                }
            }
        }
        //获取出勤表中所有有过记录的人名(不重复的)names
        List<String> names = attendanceService.getNames();
        //定义三个数组用来存储横坐标和两个纵坐标
        String[] loginNameX = new String[names.size()];
        Integer[] inStatusY = new Integer[names.size()];
        Integer[] outStatusY = new Integer[names.size()];
        //遍历names,将name与对应的inStatusCount和outStatusCount加进3个不同的数组中
        for (int i = 0; i < names.size(); i++) {
            String name = names.get(i);
            loginNameX[i] = name;
            if (inStatusMap.get(name)==null){
                inStatusY[i] = 0;
            }else {
                inStatusY[i] = inStatusMap.get(name);
            }
            if (outStatusMap.get(name)==null){
                outStatusY[i] = 0;
            }else {
                outStatusY[i] = outStatusMap.get(name);
            }
        }
        //将三个数组加进mapNew集合中，返回mapNew
        HashMap<String, Object> newMap = new HashMap<>();
        newMap.put("loginNameX",loginNameX);
        newMap.put("inStatusY",inStatusY);
        newMap.put("outStatusY",outStatusY);
        System.out.println(Arrays.toString(loginNameX)+"lllllllllllllllllllllllllllllllllllllllll");
        System.out.println(Arrays.toString(inStatusY));
        System.out.println(Arrays.toString(outStatusY));
        return new Result(ReturnStatus.SUCCESS.getCode(), ReturnStatus.SUCCESS.getMessage(),
                0, newMap);
    }

    /** 
     * @create by: 卫子健
     * @description: 工具方法 查询attendancesNew 
     * @create time: 2021/3/26 16:28
     * @param page limit  attendance
     * @return  
     */
    ArrayList<Attendance> findAttendancesNew(Integer page, Integer limit, Attendance attendance){
        if (attendance.getAttendanceTime()==null||attendance.getAttendanceTime()==""){
            //默认查询当天的考勤数据
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            String nowDay = simpleDateFormat1.format(new Date());
            attendance.setAttendanceTime(nowDay);
        }
        PageInfo PageInfo = attendanceService.queryAll(page, limit, attendance);
        List<Attendance> attendances = PageInfo.getList();
        //用来返回的新的list集合
        ArrayList<Attendance> attendancesNew = new ArrayList<>();
        //设置签到，签退时间
        int size = attendances.size();
        for (int i = 0; i < size-1; i++) {
            for (int j = i+1; j < size; j++) {
                Attendance attendance1 = attendances.get(i);
                Attendance attendance2 = attendances.get(j);
                if (attendance1.getUserId().equals(attendance2.getUserId())){
                    String[] attendance1Time = attendance1.getAttendanceTime().split(" ")[1].split(":");
                    String[] attendance2Time = attendance2.getAttendanceTime().split(" ")[1].split(":");
                    //判断小时
                    if (Integer.parseInt(attendance1Time[0])>Integer.parseInt(attendance2Time[0])){
                        //设置签到时间
                        attendance1.setCheckIn(attendance2.getAttendanceTime());
                        //设置签退时间
                        attendance1.setCheckOut(attendance1.getAttendanceTime());
                    }else if (Integer.parseInt(attendance1Time[0])==Integer.parseInt(attendance2Time[0])){
                        //判断分钟
                        if (Integer.parseInt(attendance1Time[1])>Integer.parseInt(attendance2Time[1])){
                            //设置签到时间
                            attendance1.setCheckIn(attendance2.getAttendanceTime());
                            //设置签退时间
                            attendance1.setCheckOut(attendance1.getAttendanceTime());
                        }else if(Integer.parseInt(attendance1Time[1])==Integer.parseInt(attendance2Time[1])){
                            //判断秒
                            if (Integer.parseInt(attendance1Time[2])>Integer.parseInt(attendance2Time[2])){
                                //设置签到时间
                                attendance1.setCheckIn(attendance2.getAttendanceTime());
                                //设置签退时间
                                attendance1.setCheckOut(attendance1.getAttendanceTime());
                            }else if(Integer.parseInt(attendance1Time[2])==Integer.parseInt(attendance2Time[2])){
                                //设置签到时间
                                attendance1.setCheckIn(attendance2.getAttendanceTime());
                                //设置签退时间
                                attendance1.setCheckOut(attendance1.getAttendanceTime());
                            }else {
                                //设置签到时间
                                attendance1.setCheckIn(attendance1.getAttendanceTime());
                                //设置签退时间
                                attendance1.setCheckOut(attendance2.getAttendanceTime());
                            }
                        }else {
                            //设置签到时间
                            attendance1.setCheckIn(attendance1.getAttendanceTime());
                            //设置签退时间
                            attendance1.setCheckOut(attendance2.getAttendanceTime());
                        }
                    }else {
                        //设置签到时间
                        attendance1.setCheckIn(attendance1.getAttendanceTime());
                        //设置签退时间
                        attendance1.setCheckOut(attendance2.getAttendanceTime());
                    }
                    attendancesNew.add(attendance1);
                }
            }
        }
        //设置早退，迟到状态
        for (Attendance attendance1 : attendancesNew) {
            //设置迟到状态
            if (Integer.parseInt(attendance1.getCheckIn().split(" ")[1].split(":")[0])<9){
                attendance1.setInStatus(false);
            }else {
                attendance1.setInStatus(true);
            }
            //设置早退状态
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date checkIn = simpleDateFormat.parse(attendance1.getCheckIn());
                Date checkOut = simpleDateFormat.parse(attendance1.getCheckOut());
                long in = checkIn.getTime();
                long out = checkOut.getTime();
                long i = out-in;
                int k = 8*60*60*1000;
                if ((i-k)>0){
                    attendance1.setOutStatus(false);
                }else {
                    attendance1.setOutStatus(true);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return attendancesNew;
    }
}
